package com.yix.admin.modules.system.service.impl;

import com.yix.admin.modules.system.entity.SysDept;
import com.yix.admin.modules.system.entity.dto.SysRoleSmallDto;
import com.yix.admin.modules.system.entity.dto.SysUserDto;
import com.yix.admin.modules.system.service.DataService;
import com.yix.admin.modules.system.service.SysDeptService;
import com.yix.admin.modules.system.service.SysRoleService;
import com.yix.common.utils.enums.DataScopeEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author wdx
 * @version 1.0
 * @Description TODO
 * @date 2021/2/2 13:55
 */
@Service
@CacheConfig(cacheNames = "data")
public class DataServiceImpl implements DataService {

    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysDeptService sysDeptService;
    /**
     * 用户角色改变时需清理缓存
     * @param user /
     * @return /
     */
    @Override
    @Cacheable(key = "'user:' + #p0.id")
    public List<String> getDeptIds(SysUserDto user) {
        // 用于存储部门id
        Set<String> deptIds = new HashSet<>();
        // 查询用户角色
        List<SysRoleSmallDto> roleSet = sysRoleService.findByUsersId(user.getId());
        // 获取对应的部门ID
        for (SysRoleSmallDto role : roleSet) {
            DataScopeEnum dataScopeEnum = DataScopeEnum.find(role.getDataScope());
            switch (Objects.requireNonNull(dataScopeEnum)) {
                case THIS_LEVEL:
                    deptIds.add(user.getDept().getId());
                    break;
                case CUSTOMIZE:
                    deptIds.addAll(getCustomize(deptIds, role));
                    break;
                default:
                    return new ArrayList<>(deptIds);
            }
        }
        return new ArrayList<>(deptIds);
    }

    /**
     * 获取自定义的数据权限
     * @param deptIds 部门ID
     * @param role 角色
     * @return 数据权限ID
     */
    public Set<String> getCustomize(Set<String> deptIds, SysRoleSmallDto role){
        Set<SysDept> depts = sysDeptService.findByRoleId(role.getId());
        for (SysDept dept : depts) {
            deptIds.add(dept.getId());
            List<SysDept> deptChildren = sysDeptService.findByPid(dept.getId());
            if (deptChildren != null && deptChildren.size() != 0) {
                deptIds.addAll(sysDeptService.getDeptChildren(deptChildren));
            }
        }
        return deptIds;
    }
}
